<template>
  <div class="list-common-table">
    <t-form ref="form" :data="searchModel" :label-width="80" colon @reset="reset" @submit="search">
      <t-row>
        <t-col :span="10">
          <t-row :gutter="[24, 24]">
            <t-col :span="4">
              <t-form-item label="用户名" name="username">
                <t-input v-model="searchModel.username" class="form-item-content" type="search" />
              </t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item label="手机号" name="phone">
                <t-input v-model="searchModel.phone" class="form-item-content" type="tel" />
              </t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item label="是否锁定" name="lockFlag">
                <t-select v-model="searchModel.lockFlag" class="form-item-content" :options="NORMAL_STATUS" clearable />
              </t-form-item>
            </t-col>
          </t-row>
        </t-col>

        <t-col :span="2" class="operation-container">
          <t-button theme="primary" type="submit" :style="{ marginLeft: 'var(--td-comp-margin-s)' }">
            <template #icon><search-icon /></template>
            查询
          </t-button>
          <t-button type="reset" variant="base" theme="default">
            <template #icon><rollback-icon /></template>
            重置
          </t-button>
        </t-col>
      </t-row>
    </t-form>

    <t-divider />
    <t-row justify="space-between">
      <t-button v-permission="authority.SYS_USER_ADD" @click="add">
        <template #icon><add-icon /></template>
        新建
      </t-button>
    </t-row>

    <div class="table-container">
      <t-table
        :data="renderData"
        :columns="columns"
        row-key="id"
        :hover="true"
        :pagination="pagination"
        :loading="loading"
        :header-affixed-top="headerAffixedTop"
        table-layout="auto"
        size="small"
        @page-change="pageChange"
      >
        <template #role="{ row }">
          {{ getRoleNames(row.roleIds) }}
        </template>
        <template #lockFlag="{ row }">
          <t-tag v-if="row.lockFlag === NormalState.YES" theme="danger" variant="light"> 是 </t-tag>
          <t-tag v-else theme="success" variant="light"> 否 </t-tag>
        </template>
        <template #operations="{ row }">
          <t-space>
            <t-button
              v-permission="authority.SYS_USER_EDIT"
              variant="text"
              size="small"
              theme="primary"
              @click="edit(row)"
            >
              <template #icon>
                <edit-icon />
              </template>
              编辑
            </t-button>
            <t-button
              v-permission="authority.SYS_USER_PASSWORD"
              variant="text"
              size="small"
              theme="primary"
              @click="password(row)"
            >
              <template #icon>
                <user-password-icon />
              </template>
              修改密码
            </t-button>
            <t-popconfirm
              :content="`此操作将永久删除该用户(${row.username}), 是否继续?`"
              theme="danger"
              @confirm="del(row.id)"
            >
              <t-button v-permission="authority.SYS_USER_DEL" variant="text" size="small" theme="danger">
                <template #icon>
                  <delete-icon />
                </template>
                删除
              </t-button>
            </t-popconfirm>
          </t-space>
        </template>
      </t-table>
    </div>
    <user-form v-model:visible="formDialogVisible" :form-data="formData" @refresh="refresh" />
    <password-form v-model:visible="pwdModalVisible" :form-data="pwdData" />
  </div>
</template>
<script setup lang="ts">
import { pickBy } from 'lodash';
import { AddIcon, DeleteIcon, EditIcon, RollbackIcon, SearchIcon, UserPasswordIcon } from 'tdesign-icons-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';
import { computed, ref } from 'vue';
import { usePagination, useRequest } from 'vue-request';

import { getRoleList } from '@/api/upms/role';
import { deleteUser, getUserPage } from '@/api/upms/user';
import PasswordForm from '@/components/password/index.vue';
import { prefix } from '@/config/global';
import { NORMAL_STATUS, NormalState } from '@/constants';
import { useSettingStore } from '@/store';
import authority from '@/utils/authority';
import defaultPageOptions from '@/utils/pagination';

import UserForm from './components/user-form.vue';

// 初始数据
const generateModel = () => {
  return {
    username: '',
    phone: '',
    lockFlag: '',
  };
};

const searchModel = ref(generateModel());

const formData = ref({});

const store = useSettingStore();

const columns = [
  { title: 'ID', colKey: 'id' },
  { title: '账号', colKey: 'username' },
  { title: '所属机构', colKey: 'orgName' },
  { title: '角色', colKey: 'role' },
  { title: '手机号', colKey: 'phone' },
  { title: '创建时间', colKey: 'createTime' },
  { title: '是否锁定', colKey: 'lockFlag' },
  { title: '操作', colKey: 'operations' },
];

const renderData = computed(() => data.value?.records || []);

const pagination = computed(() => ({
  current: current.value,
  pageSize: pageSize.value,
  showTotal: true,
  showPageSize: true,
  total: total.value,
}));

const { data, loading, refresh, current, pageSize, total } = usePagination(
  (params) => getUserPage({ ...params, ...pickBy(searchModel.value) }),
  {
    ...defaultPageOptions,
  },
);

// 弹出框标记
const formDialogVisible = ref(false);

const pwdModalVisible = ref(false);

const pwdData = ref({
  title: '',
  userId: '',
});

const password = (e: any) => {
  pwdModalVisible.value = true;
  pwdData.value.title = `修改用户${e.username}的密码`;
  pwdData.value.userId = e.id;
};

const pageChange = (curr: any) => {
  if (pageSize.value !== curr.pageSize) {
    pageSize.value = curr.pageSize;
  }
  if (current.value !== curr.current) {
    current.value = curr.current;
  }
};

const search = () => {
  current.value = 1;
};

const reset = () => {
  searchModel.value = generateModel();
};

const add = () => {
  formDialogVisible.value = true;
  formData.value = {};
};
const edit = (e: any) => {
  formDialogVisible.value = true;
  formData.value = { ...e };
};
const del = async (id: string) => {
  await deleteUser(id).then(() => {
    MessagePlugin.success('删除成功');
    refresh();
  });
};

const { data: roles } = useRequest(getRoleList);

const getRoleNames = (roleIds: []) =>
  roleIds?.map((id: any) => roles.value?.find((r: { id: any }) => r.id === id)?.roleName ?? '')?.join(' , ');

const headerAffixedTop = computed(
  () =>
    ({
      offsetTop: store.isUseTabsRouter ? 48 : 0,
      container: `.${prefix}-layout`,
    }) as any, // TO BE FIXED
);
</script>

<style lang="less" scoped>
.list-common-table {
  background-color: var(--td-bg-color-container);
  padding: var(--td-comp-paddingTB-xxl) var(--td-comp-paddingLR-xxl);
  border-radius: var(--td-radius-medium);

  .table-container {
    margin-top: var(--td-comp-margin-xxl);
  }
}

.form-item-content {
  width: 100%;
}

.operation-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;

  .expand {
    .t-button__text {
      display: flex;
      align-items: center;
    }
  }
}

.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: var(--td-comp-margin-s);
  }
}
</style>
